package com.salatigacode.customerdatabase.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.salatigacode.customerdatabase.entity.Customer;

public class CustomerDAO {
	
	private Connection conn;
	
	public CustomerDAO(Connection conn){
		this.conn = conn;
	}
	
	public List<Customer> getAllCustomer(){
		List<Customer> customers = new ArrayList<Customer>();
		String sql = "SELECT id,firstname,lastname,phone,email FROM tbl_customer";
		PreparedStatement pst = null;
		try{
			pst = this.conn.prepareStatement(sql);
			ResultSet rs = pst.executeQuery();
			while(rs.next()){
				Customer customer = new Customer();
				customer.setId(rs.getInt(1));
				customer.setFirstName(rs.getString(2));
				customer.setLastName(rs.getString(3));
				customer.setPhone(rs.getString(4));
				customer.setEmail(rs.getString(5));
				customers.add(customer);
			}
		}catch(Exception ex){
			System.err.println(ex.getMessage());
		}
		return customers;
	}
	
	public void insert(Customer customer){
		String sql = "INSERT INTO tbl_customer(firstname,lastname,phone,email) "
				+ "VALUES(?,?,?,?)";
		PreparedStatement ps = null;
		try{
			ps = this.conn.prepareStatement(sql);
			ps.setString(1, customer.getFirstName());
			ps.setString(2,customer.getLastName());
			ps.setString(3,customer.getPhone());
			ps.setString(4,customer.getEmail());
			ps.executeUpdate();
		}catch(Exception ex){
			System.err.println(ex.getMessage());
		}
	}
	
	public void delete(int id){
		String sql = "DELETE FROM tbl_customer WHERE id=?";
		PreparedStatement ps = null;
		try{
			ps = this.conn.prepareStatement(sql);
			ps.setInt(1, id);
			ps.executeUpdate();
		}catch(Exception ex){
			System.err.println(ex.getMessage());
		}
	}
}
